import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/index'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: () => import('@/views/login/LoginPage.vue')
    },
    {
      path: '/borrower',
      component: () => import('@/views/borrowers/layout/BorrowerLayout.vue'),
      redirect: '/borrower/bookBorrow',
      children: [
        {
          path: '/borrower/bookBorrow',
          component: () => import('@/views/borrowers/bookBorrow/bookBorrow.vue')
        },
        {
          path: '/borrower/myBorrwer',
          component: () => import('@/views/borrowers/MyBorrow/myBorrwer.vue')
        }
      ]
    },
    {
      path: '/admin',
      component: () => import('@/views/admin/layout/AdminLayout.vue'),
      redirect: '/admin/bookManage',
      children: [
        {
          path: '/admin/borrowerManage',
          component: () =>
            import('@/views/admin/borrowersManage/borrowersManage.vue')
        },
        {
          path: '/admin/bookManage',
          component: () => import('@/views/admin/bookManage/bookManage.vue')
        },
        {
          path: '/admin/orderManage',
          component: () => import('@/views/admin/orderManage/orderManage.vue')
        }
      ]
    }
  ]
})

router.beforeEach((to) => {
  const userStore = useUserStore()
  if (!userStore.token && to.path !== '/') {
    return '/'
  } else if (to.path === '/') {
    userStore.reset()
  }
})

export default router
